package harvard.cscie160.hw7.project;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;

/**
 * SecurityInterface and SecurityImpl used jointly together
 * to get around inheritance limitations in Java.  As we need
 * to extend both Remote and UnicastRemoteObject an Interface is 
 * used to get around single inheritance.
 * @author M. Bret Blackford
 *
 */
public class SecurityImpl extends UnicastRemoteObject implements SecurityInterface {
	
	private HashMap<Integer, SecurityRecord> securityAccess;
	private static SecurityImpl securityInstance;

	private SecurityImpl() throws RemoteException {
		securityAccess = new HashMap<Integer, SecurityRecord>();
	}

	public static SecurityImpl getSecurityInstance() throws RemoteException {
		if (securityInstance == null) {
			securityInstance = new SecurityImpl();
		}

		return securityInstance;
	}

	
	public void setSecurityAccess(int accountNumber, String PIN,
			boolean depositPermitted, boolean withdrawPermitted,
			boolean balancePermitted) {
		
		SecurityRecord securityRecord = securityAccess.get(accountNumber);
		
		if (securityRecord == null) {
			securityRecord = new SecurityRecord();
			securityAccess.put(accountNumber, securityRecord);
		}

		securityRecord.setPIN(PIN);
		securityRecord.setAuthorization(OperationEnumType.DEPOSIT, depositPermitted);
		securityRecord.setAuthorization(OperationEnumType.WITHDRAWAL, withdrawPermitted);
		securityRecord.setAuthorization(OperationEnumType.BALANCE, balancePermitted);
	}

	
	private SecurityRecord getSecurityRecord(int accountNumber) throws ATMException {
		
		SecurityRecord securityRecord = securityAccess.get(accountNumber);
		
		if (securityRecord == null) {
			System.out.println(DateUtils.now() + " ERROR in SecurityImpl.getRecord()");
			throw new ATMException("ERROR: unknown permission for account "
					+ accountNumber);
		}

		return securityRecord;
	}


	public boolean checkSecurityAccess(int accountNumber, OperationEnumType type)
			throws ATMException {
		SecurityRecord securityRecord = getSecurityRecord(accountNumber);
		return securityRecord.getAuthorization(type);
	}

	//Having trouble with this
	public boolean checkPIN(int accountNumber, String PIN) throws ATMException {
		SecurityRecord record = getSecurityRecord(accountNumber);
		Integer recPIN = new Integer(record.getPIN());
		Integer inPIN = new Integer(PIN);
/*		if (recPIN != inPIN){
			throw new ATMException("PROBLEM WITH PIN");
		}*/
		return record.getPIN().equals(PIN);
	}
	
	//Having trouble with this
/*	public boolean checkPIN(int accountNumber, int PIN) throws ATMException {
		SecurityRecord record = getSecurityRecord(accountNumber);
		Integer recPIN = new Integer(record.getPIN());
		if (recPIN != PIN) {
			throw new ATMException("PROBLEM WITH PIN");
		}
		
		return record.getPIN().equals(PIN);
	}*/

}

